import os
import sys
import requests
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QLabel, QWidget, QToolButton, QTextEdit, QLabel
from PyQt6.uic import loadUi
from PyQt6.QtCore import QTimer, Qt, QUrl
from PyQt6.QtGui import QDesktopServices
from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtCore import QSettings
from datetime import datetime
import json

from roll_call_module import RollCallDialog
from timetable_module import TimetableModule
from auto_cctv_controller import AutoCCTVController  # 导入自动新闻联播模块
from shutdown_module import ShutdownModule  # 导入关机模块
from time_module import TimeModule  # 导入时间模块
from weather_module import WeatherModule
from settings_window import SettingsWindow  # 导入设置窗口类
from bulletin_board_module import BulletinBoardModule  # 导入公告板模块



class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 加载 .ui 文件
        loadUi('./ui/mainwindow.ui', self)  # 替换为实际路径

        # 初始化各个模块
        self.init_modules()

        # 设置定时器每分钟更新一次
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_timetable)
        self.timer.start(60000)  # 每分钟更新

        # 初始更新
        self.update_timetable()

        # 调用 setup_weather_module 方法并添加调试信息
        self.setup_weather_module()

        # 启动定时器以每分钟检查一次设置
        self.settings_timer = QTimer(self)
        self.settings_timer.timeout.connect(self.check_settings)
        self.settings_timer.start(60000)  # 每分钟检查一次设置

        # 初始化时间模块
        self.time_module = TimeModule(self)

        # 保存和恢复窗口大小和位置
        self.restore_window_geometry()

        # 连接 toolButton_3 到打开设置窗口的方法
        self.toolButton_3.clicked.connect(self.open_settings_window)

        self.toolButton.clicked.connect(self.open_roll_call_window)  # 打开点名窗口的按钮

        # 初始化公告板模块
        self.init_bulletin_board_module()

        # 找到 label_update 控件
        self.label_update = self.findChild(QLabel, "label_update")
        if self.label_update is None:
            raise ValueError("找不到 label_update，请检查 UI 文件")

        # 在启动时检测更新
        self.check_for_updates()

        # 移除窗口边框
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        # 固定窗口位置和大小
        self.fix_window_position_and_size()

        # 将窗口置于最下层
        self.lower()


    def fix_window_position_and_size(self):
        # 获取屏幕的尺寸
        screen = QApplication.primaryScreen().geometry()
        screen_width = screen.width()
        screen_height = screen.height()

        # 获取任务栏的高度
        taskbar_height = self.get_taskbar_height()

        # 确保任务栏高度合理
        if taskbar_height >= screen_height:
            taskbar_height = 25  # 使用默认任务栏高度

        # 计算窗口的宽度和高度
        window_width = screen_width // 3
        window_height = screen_height - taskbar_height

        # 确保窗口高度不为负数
        if window_height <= 0:
            window_height = screen_height - 25  # 使用默认任务栏高度

        # 计算窗口的位置
        window_x = screen_width - window_width
        window_y = 0

        # 设置窗口的位置和大小
        self.setGeometry(window_x, window_y, window_width, window_height)

    def get_taskbar_height(self):
        """获取任务栏的高度"""
        screen = QApplication.primaryScreen()
        available_geometry = screen.availableGeometry()
        screen_geometry = screen.geometry()

        # 获取屏幕的高度
        screen_height = screen_geometry.height()

        # 获取任务栏的高度
        taskbar_height = screen_height - available_geometry.height()

        return taskbar_height

    def show_message(self, message):
        # 创建 QMessageBox
        msg_box = QMessageBox(self)
        msg_box.setText(message)
        msg_box.setWindowTitle("提示")
        msg_box.setIcon(QMessageBox.Icon.Information)

        # 显示消息框并设置自动关闭
        msg_box.show()
        QTimer.singleShot(2000, msg_box.close)  # 2秒后关闭消息框

    def status_callback(self, message):
        # 使用 show_message 方法显示消息
        self.show_message(message)

    def init_modules(self):
        self.timetable_module = TimetableModule(self)
        self.shutdown_module = None
        self.cctv_controller = None
        self.load_settings()  # 确保设置已加载
        self.init_shutdown_module()  # 在设置加载后初始化关机模块
        self.init_news_module()

    def update_timetable(self):
        current_time = datetime.now().time()
        self.timetable_module.update_timetable(current_time)

    def load_settings(self):
        """加载设置"""
        try:
            with open('data/launch.json', 'r', encoding='utf-8') as file:
                settings = json.load(file)
                self.shutdown_status = settings.get('shutdown', '关闭')
                self.news_status = settings.get('news', '关闭')
        except (FileNotFoundError, json.JSONDecodeError):
            self.shutdown_status = '关闭'
            self.news_status = '关闭'

    def check_settings(self):
        """检查设置并更新状态"""
        self.load_settings()

    def init_news_module(self):
        """根据设置初始化新闻联播模块"""
        if self.news_status == '开启':
            if not hasattr(self, 'cctv_controller') or self.cctv_controller is None:
                self.cctv_controller = AutoCCTVController()  # 确保初始化时自动启动定时器
        elif self.news_status == '关闭' and hasattr(self, 'cctv_controller'):
            if self.cctv_controller is not None:
                self.cctv_controller.stop_timers()
            del self.cctv_controller

    def init_shutdown_module(self):
        """根据设置初始化关机模块"""
        if self.shutdown_status == '开启':
            if not hasattr(self, 'shutdown_module') or self.shutdown_module is None:
                self.shutdown_module = ShutdownModule(self)  # 传递 self 作为父窗口引用
        elif self.shutdown_status == '关闭' and hasattr(self, 'shutdown_module'):
            if self.shutdown_module is not None:
                self.shutdown_module.stop()  # 确保 self.shutdown_module 不是 None
            del self.shutdown_module
            self.shutdown_module = None  # 清除引用

    def setup_weather_module(self):
        widget_2 = self.findChild(QWidget, "widget_2")
        if widget_2 is not None:
            self.weather_module = WeatherModule(widget_2)
            layout = QVBoxLayout()
            layout.addWidget(self.weather_module)
            widget_2.setLayout(layout)
        else:
            self.show_message("找不到 widget_2，请检查 UI 文件")

    def restore_window_geometry(self):
        """恢复窗口大小和位置"""
        settings = QSettings("Log", "EC")

        # 恢复窗口几何信息
        geometry = settings.value("windowGeometry")
        if geometry:
            self.restoreGeometry(geometry)
        else:
            # 如果没有保存的几何信息，使用默认值
            default_width = 400
            default_height = 600
            self.resize(default_width, default_height)

        # 恢复窗口位置
        position = settings.value("windowPosition")
        if position:
            self.move(position)
        else:
            # 如果没有保存的位置信息，使用默认值
            default_x = 100
            default_y = 100
            self.move(default_x, default_y)

    def closeEvent(self, event):
        """在窗口关闭时保存窗口大小和位置，并恢复嵌入的窗口到桌面或终止其进程"""
        settings = QSettings("Log", "EC")
        settings.setValue("windowGeometry", self.saveGeometry())
        settings.setValue("windowPosition", self.pos())

        event.accept()

    def open_settings_window(self):
        # 创建并显示设置窗口
        settings_window = SettingsWindow(self)
        settings_window.exec()

    def init_bulletin_board_module(self):
        text_edit = self.findChild(QTextEdit, "textEdit")
        if text_edit is not None:
            self.bulletin_board_module = BulletinBoardModule(self, text_edit)
        else:
            self.show_message("找不到 textEdit，请检查 UI 文件")

    def check_for_updates(self):
        """检测最新版本并更新状态"""
        try:
            response = requests.get('https://api.github.com/repos/Return-Log/Education-Clock/tags', timeout=5)
            response.raise_for_status()
            tags = response.json()
            if tags:
                latest_tag = tags[0]['name']
                current_version = "v3.8"  # 替换为你的当前版本号
                if latest_tag != current_version:
                    self.label_update.setText(f'<a href="https://github.com/Return-Log/Education-Clock/releases/latest" style="color: red;">检测到新版本 {latest_tag}, 当前版本 {current_version}</a>')
                    self.label_update.setOpenExternalLinks(True)
                else:
                    self.label_update.setText(f'<a href="https://github.com/Return-Log/Education-Clock/releases/latest" style="color: green;">已是最新版 {latest_tag}</a>')
                    self.label_update.setOpenExternalLinks(True)
            else:
                self.label_update.setText("无法检测更新")
        except requests.RequestException:
            self.label_update.setText("无法检测更新")

    # 在 MainWindow 类中添加打开点名窗口的方法
    def open_roll_call_window(self):
        """打开随机点名窗口"""
        self.roll_call_dialog = RollCallDialog(self)
        self.roll_call_dialog.exec()

    def get_qss_path(self):
        default_qss = './ui/qss/dark.qss'
        qss_txt_path = './data/qss.txt'

        if not os.path.exists(qss_txt_path):
            return default_qss

        try:
            with open(qss_txt_path, 'r', encoding='utf-8') as f:
                qss_file = f.read().strip()
                if not qss_file:
                    return default_qss
                qss_path = os.path.join('./ui/qss', qss_file)
                if os.path.exists(qss_path):
                    return qss_path
                else:
                    self.show_message(f"QSS file {qss_file} does not exist, using default.")
                    return default_qss
        except Exception as e:
            self.show_message(f"Error reading qss.txt: {e}, using default.")
            return default_qss

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 使用 get_qss_path 方法获取 QSS 文件路径
    main_window = MainWindow()
    qss_path = main_window.get_qss_path()

    try:
        with open(qss_path, 'r', encoding="utf-8") as f:
            app.setStyleSheet(f.read())
    except Exception as e:
        MainWindow.show_message(f"Failed to load QSS file: {e}")

    window = MainWindow()
    window.show()
    sys.exit(app.exec())